package com.shlh.saas.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shlh.saas.common.Result;
import com.shlh.saas.common.UserContext;
import com.shlh.saas.entity.UserBalance;
import com.shlh.saas.entity.customs.CustomTrade;
import com.shlh.saas.model.dto.CustomsTradeInfoSearchCriteriaDTO;
import com.shlh.saas.service.UserBalanceService;
import com.shlh.saas.service.WorkbenchStatsService;
import com.shlh.saas.service.customs.CustomTradeService;
import com.shlh.saas.service.ExportRecordService;
import com.shlh.saas.util.FileUtils;
import com.shlh.saas.util.ExcelUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 海关交易信息控制器
 */
@RestController
@RequestMapping("/customs")
@Slf4j
public class CustomsTradeInfoController {

    @Autowired
    private CustomTradeService customTradeService;
    
    @Autowired
    private WorkbenchStatsService workbenchStatsService;
    
    @Autowired
    private UserBalanceService userBalanceService;
    
    @Autowired
    private ExportRecordService exportRecordService;

    /**
     * 根据条件搜索海关交易信息（分页）
     *
     * @param productKeywordEnglish 产品关键词（英文）
     * @param hsCode 海关编码
     * @param originCountry 原产国
     * @param supplierEnglish 供应商（英文）
     * @param portOfLoading 起运港
     * @param destinationCountry 目的国
     * @param purchaserEnglish 采购商（英文）
     * @param portOfDestination 目的港
     * @param startDate 交易开始日期
     * @param endDate 交易结束日期
     * @param productDescription 产品描述
     * @param page 页码 (从1开始)
     * @param size 每页大小
     * @return 分页的海关交易信息
     */
    @GetMapping("/search")
    public Result searchCustomsTradeInfos(
            @RequestParam(required = false) String productKeywordEnglish,
            @RequestParam(required = false) String hsCode,
            @RequestParam(required = false) String originCountry,
            @RequestParam(required = false) String supplierEnglish,
            @RequestParam(required = false) String portOfLoading,
            @RequestParam(required = false) String destinationCountry,
            @RequestParam(required = false) String purchaserEnglish,
            @RequestParam(required = false) String portOfDestination,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate,
            @RequestParam(required = false) String productDescription,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        log.info("搜索海关交易信息，参数: productKeywordEnglish={}, " +
                "hsCode={}, originCountry={}, supplierEnglish={}, portOfLoading={}, destinationCountry={}, purchaserEnglish={}, portOfDestination={}, startDate={}, endDate={}, productDescription={}, page={}, size={}",
                productKeywordEnglish, hsCode, originCountry, supplierEnglish, portOfLoading, destinationCountry, purchaserEnglish, portOfDestination, startDate, endDate, productDescription, page, size);
        Long userId = UserContext.getUserId();
        // 第一页不扣除额度，免费查看
        if (page == 1) {
            // 使用CustomTradeService的searchByConditions方法
            Page<CustomTrade> tradeInfosPage = customTradeService.searchByConditions(
                    productKeywordEnglish, hsCode, originCountry, destinationCountry,
                    startDate, endDate, page, size
            );
            
            // 增加搜索次数统计
            workbenchStatsService.incrementCustomsSearchCount(userId);
            
            return Result.success(tradeInfosPage);
        } else {
            // 检查用户余额
            UserBalance userBalance = userBalanceService.getByUserId(userId);
            if (userBalance == null || userBalance.getViewRecordsRemaining() < size) {
                return Result.error("您的查看记录余额不足，请充值后再查看");
            }
            
            // 查询数据
            Page<CustomTrade> tradeInfosPage = customTradeService.searchByConditions(
                    productKeywordEnglish, hsCode, originCountry, destinationCountry,
                    startDate, endDate, page, size
            );
            
            // 扣除用户查看记录余额
            userBalanceService.deductViewRecords(userId, (int) tradeInfosPage.getRecords().size());
            
            // 增加搜索次数统计
            workbenchStatsService.incrementCustomsSearchCount(userId);
            
            return Result.success(tradeInfosPage);
        }
    }

    /**
     * 获取符合条件的记录总数
     */
    @PostMapping("/count")
    public Result countCustomsTradeInfos(@RequestBody CustomsTradeInfoSearchCriteriaDTO criteria) {
        log.info("计算符合条件的海关交易信息数量，参数: {}", criteria);
        
        long count = customTradeService.countByConditions(
                criteria.getProductKeywordEnglish(),
                criteria.getHsCode(),
                criteria.getOriginCountry(),
                criteria.getDestinationCountry(),
                criteria.getStartDate(),
                criteria.getEndDate()
        );
        
        // 限制最大返回数量为100万
        if (count > 1000000) {
            count = 1000000;
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("count", count);
        return Result.success(result);
    }

    /**
     * 导出海关交易信息数据
     */
    @PostMapping("/export")
    public void exportCustomsTradeInfos(
            HttpServletResponse response,
            @RequestBody(required = false) CustomsTradeInfoSearchCriteriaDTO criteria,
            @RequestParam(required = true) Integer exportCount) {
        log.info("导出海关交易信息数据，参数: {}, 导出数量: {}", criteria, exportCount);
        
        try {
            // 获取当前用户ID
            Long userId = UserContext.getUserId();
            // 检查用户余额
            UserBalance userBalance = userBalanceService.getByUserId(userId);
            if (userBalance == null || userBalance.getExportQuotaRemaining() < exportCount) {
                response.setContentType("application/json;charset=UTF-8");
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                response.getWriter().write("{\"message\":\"您的导出次数余额不足，请充值后再导出\"}");
                return;
            }
            
            // 限制最大导出数量为100万
            if (exportCount > 1000000) {
                exportCount = 1000000;
            }
            
            // 获取数据
            List<CustomTrade> tradeInfos = customTradeService.findByConditionsForExport(
                criteria.getProductKeywordEnglish(),
                criteria.getHsCode(),
                criteria.getOriginCountry(),
                criteria.getDestinationCountry(),
                criteria.getStartDate(),
                criteria.getEndDate(),
                exportCount
            );
            
            log.info("查询到 {} 条数据准备导出", tradeInfos.size());
            
            if (tradeInfos.isEmpty()) {
                response.setContentType("application/json;charset=UTF-8");
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                response.getWriter().write("{\"message\":\"没有找到符合条件的数据\"}");
                return;
            }
            
            // 设置导出文件名和表头
            String fileName = "海关交易信息数据_" + System.currentTimeMillis() + ".xlsx";
            String[] columnNames = {"产品关键词", "海关编码", "提单号", "原产国", "供应商", 
                                   "起运港", "目的国", "采购商", "目的港", 
                                   "开始日期", "结束日期", "产品描述", "交易金额", "数量"};
            String[] fields = {"productKeywordEnglish", "hsCode", "billOfLadingNumber", 
                              "originCountry", "supplierEnglish", "portOfLoading", 
                              "destinationCountry", "purchaserEnglish", "portOfDestination", 
                              "startDate", "endDate", "productDescription", "totalAmount", "quantity"};
            
            // 扣除用户导出次数余额
            userBalanceService.deductExportQuota(userId, tradeInfos.size());
            
            // 增加导出次数统计
            workbenchStatsService.incrementCustomsExportCount(userId, tradeInfos.size());
            
            // 获取当前时间戳作为文件名一部分
            String filePath = "/export/" + fileName;
            
            // 计算文件大小（以KB为单位）
            String fileSize = FileUtils.estimateExcelSize(tradeInfos.size()) + "KB";
            
            // 保存导出记录
            exportRecordService.addExportRecord(
                userId,
                fileName,
                "customs-trade-info", // 数据来源
                fileSize,
                tradeInfos.size(),
                filePath
            );
            
            log.debug("第一条数据示例: {}", tradeInfos.get(0));
            ExcelUtils.exportExcel(response, tradeInfos, fileName, columnNames, fields);
            log.info("数据导出成功");
        } catch (Exception e) {
            log.error("导出海关交易信息数据失败", e);
            try {
                response.reset();
                response.setContentType("application/json;charset=UTF-8");
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                response.getWriter().write("{\"message\":\"导出数据失败: " + e.getMessage() + "\"}");
            } catch (IOException ex) {
                log.error("写入错误响应失败", ex);
            }
        }
    }

    /**
     * 获取所有产品关键词
     *
     * @return 产品关键词列表
     */
    @GetMapping("/product-keywords")
    public Result<List<String>> getAllProductKeywords() {
        log.info("获取所有产品关键词");
        try {
            List<String> keywords = customTradeService.getAllProductKeywords();
            return Result.success(keywords);
        } catch (Exception e) {
            log.error("获取产品关键词失败", e);
            return Result.error("获取产品关键词失败: " + e.getMessage());
        }
    }

    /**
     * 获取所有海关编码
     *
     * @return 海关编码列表
     */
    @GetMapping("/hs-codes")
    public Result<List<String>> getAllHsCodes() {
        log.info("获取所有海关编码");
        try {
            List<String> hsCodes = customTradeService.getAllHsCodes();
            return Result.success(hsCodes);
        } catch (Exception e) {
            log.error("获取海关编码失败", e);
            return Result.error("获取海关编码失败: " + e.getMessage());
        }
    }
}

